import welfareList from '../../pages/index/components/welfare_purchase.vue'
import menberList from './components/menberList.vue'
import automaticList from './components/automatic.vue'
import recommend from './components/recommend.vue'
const dayjs = require('@/utils/dayjs.js')
export default {
  components: {
    welfareList,
    menberList,
    automaticList,
    recommend
  },
  data(){
    return {
      emptyShow: false,//是否显示空白图
      id: '',
      current: null,
      couponInfo: null,
      show: false,
      couponNum: 0, // 优惠券数量
      isAgreement: false, // 是否勾选协议
      currentTab: 0,

      pageLoading: false,
      loadStatus: '',
      pageIndex: 1,//当前页
      list2: [],//列表数据
      currentSwiper: 0,//当前页
      //tab标签
      list: [
        /* {
          index: 0,
          name: '推荐'
        },
        {
          index: 1,
          name: '自助洗车'
        }, */
        {
          index: 2,
				  name: '自动洗车'
        },
        {
          index: 3,
          name: '我的礼卡/券'
        },

      ],

      cardList: {
        0: {
          month: [], // 月
          second: [], // 次
          minute: [], // 分钟
          recharge: [], // 计费
          speed: [],//自动
          standard: [],//标准
          delicate: [],//精致
          speedMonth: []
        },
        1: {
          month: [], // 月
          second: [], // 次
          minute: [], // 分钟
          recharge: [], // 计费
          speed: [],//自动
          standard: [],//标准
          delicate: [],//精致
          speedMonth: []
        },
        2: {
          month: [], // 月
          second: [], // 次
          minute: [], // 分钟
          recharge: [], // 计费
          speed: [],//自动
          standard: [],//标准
          delicate: [],//精致
          speedMonth: []
        },
      },
      //洗车
    }
  },

  created(){
    //福利购
    // this.getBuyDiscountsList()
    //洗车
    this.getCardList()
    this.getBuyCardList()
  },
  filters: {
	  cutString(str, len) {
	    if (str.length * 2 <= len) {
	      return str
	    }
	    let strlen = 0
	    let s = ''
	    for (let i = 0; i < str.length; i++) {
	      s = s + str.charAt(i)
	      if (str.charCodeAt(i) > 128) {
	        strlen = strlen + 2
	        if (strlen >= len) {
	          return s.substring(0, s.length - 1) + '...'
	        }
	      } else {
	        strlen = strlen + 1
	        if (strlen >= len) {
	          return s.substring(0, s.length - 2) + '...'
	        }
	      }
	    }
	    return s
	  },
  },
  computed: {
    purchaseChannel() {
		  return this.$store.state.purchaseChannel
    },
	  amount() {
	    let price = 0
	    if(this.current) {
	      if(this.couponInfo) {
	        price = Number(this.current.sale_Price) - this.couponInfo.couponAllMoney
	      } else {
	        price = Number(this.current.sale_Price)
	      }
	    } else {
	      price = 0
	    }
	    return parseFloat(price).toFixed(2)
	  }
  },
  onLoad(options) {
	  this.machineId = options.machineId || ''
    if(options.index){
      this.currentSwiper = Number(options.index)
      this.currentTab = Number(options.index)
    }
    if(options.id){
      this.id = options.id
    }
	  uni.$on('changeWashCoupon', data => {
	    // this.couponInfo = data
      this.couponInfo = data
	  })
  },
  methods: {
    //列表
    async getCardList(){
      uni.showLoading()
      try{
        let data = {
          'pageIndex': 1,
          'pageSize': 100,
          'cardType': 2	//'cardType': this.currentSwiper+1
        }
        const res = await this.$api.selfServiceCarWash.getSelfServiceCarWashCardByTypeList(data)
        if(res.code === 200) {
          let list = res.data.list.find(v => this.id===v.id)
          if(this.id){
            this.onClickItem(list)
          }
				  res.data.list.map(item => {
				    if(item.card_Type === 1) {
				      this.cardList[this.currentSwiper].month.push(item)
				    } else if(item.card_Type === 2) {
				      this.cardList[this.currentSwiper].second.push(item)
				    } else if(item.card_Type === 3) {
				      this.cardList[this.currentSwiper].minute.push(item)
				    } else if(item.card_Type === 4) {
				      this.cardList[this.currentSwiper].recharge.push(item)
				    } else if(item.card_Type === 50) {//极速次卡
              // this.cardList[this.currentSwiper].speed.push(item)
            } else if(item.card_Type === 51) {//标准次卡
              // this.cardList[this.currentSwiper].standard.push(item)
            }else if(item.card_Type === 52) {//精洗次卡
              // this.cardList[this.currentSwiper].delicate.push(item)
            }else if(item.card_Type === 53) {//极速月卡
              // this.cardList[this.currentSwiper].speedMonth.push(item)
            }
				  })
				  // this.cardList = result
          if(res.data.list.length===0){
            this.emptyShow = true
          }else{
            this.emptyShow = false
          }
        }
        this.pageLoading = true
        uni.hideLoading()
      }catch(e){
        uni.hideLoading()
      }
    },
    onClickItem(item){
      console.log(item)
      //半自动
      if(item.card_Type===1||item.card_Type===2){
				    const start = Date.parse(new Date())
				    const end = Date.parse(item.deadline)
				    if(start>end){
						  uni.showToast({
						    title: '该会员卡已过期',
						    icon: 'none'
						  })
							 return false
				    }
				  }
				  this.current = item
				  this.couponInfo = null
				  this.show = true
    },
    // 关闭弹窗
    onClosePopup() {
		  this.show = false
		  this.current = null
		  this.couponInfo = null
      this.isAgreement = false
      this.id = ''
    },
    // 获取可用优惠券数量
    async getBuyCardList() {
		  try{
		    let res = await this.$api.user.GetMyUsableSelfServiceCarWashCouponDetails({
		      pageIndex: 1,
		      pageSize: 1
		    })
		    if(res.code === 200) {
		      this.couponNum = res.data.total
		    }
		  }catch(e){
		    //TODO handle the exception
		  }
    },
    // 清除优惠券
    onClearCoupon() {
		  this.couponInfo = null
    },
    // 点击选择优惠券
    onClickCoupon(num, type) {
		  let userinfo = uni.getStorageSync('Ztc_C_USER_INFO') || null
		  if(num <= 0 || !userinfo) return false
		  uni.navigateTo({
		    url: `/pages_userModule/myCoupon/chooseWash?amount=${this.current.sale_Price}`
		  })
    },
    // 点击去支付
    async onSubmit() {
		  if(!this.isAgreement) {
		    uni.showToast({
		      icon: 'none',
		      title: '请同意说明及规定后支付'
		    })
		    return false
		  }
      //半自动下单
      if(this.current.card_Type===1||this.current.card_Type===2||this.current.card_Type===3||this.current.card_Type===4){
        uni.showLoading({
				  title: '加载中'
        })
        try{
				  let params = {
				    self_Service_Car_Wash_Card_Id: this.current.id,
				    purchase_Channel: this.purchaseChannel ? 2 : 1 // 购买途径 1：线上 2：线下
				  }
				  if(this.couponInfo) {
				    params.couponId = this.couponInfo.id
				    params.coupon_Details_Id = this.couponInfo.coupon_Details_Id
				  }
				  if(this.machineId) {
				    params.wash_Machine_Id = this.machineId
				  }

				  let res = await this.$api.selfServiceCarWash.AddSelfServiceCarWashDiscountOrder(params)
				  uni.hideLoading()
				  if(res.code === 200) {
            this.show = false
				    /* uni.redirectTo({
				      url: `/pages_commodity/payment/payment?orderNo=${res.data}&type=selfServiceCarWashCoupon&price=${this.amount}&machineId=${this.machineId}`
				    }) */
				    uni.navigateTo({
						  url: `/pages_commodity/newPay/newPay?orderNo=${res.data}&type=selfServiceCarWashCoupon&price=${this.amount}&machineId=${this.machineId}`
				    })
				  } else {
				    uni.showToast({
				      icon: 'none',
				      title: res.msg
				    })
				  }
        } catch(e) {
				  uni.showToast({
				    icon: 'none',
				    title: e.msg
				  })
        }
      }else{	//全自动下单
        try{
        	let params = {
        	  self_Service_Car_Wash_Card_Id: this.current.id,
        	  purchase_Channel: this.purchaseChannel ? 2 : 1, // 购买途径 1：线上 2：线下
            isHelpWashCar: false,
            buyWashCarCardId: this.current.id
        	}
        	if(this.couponInfo) {
        	  params.couponId = this.couponInfo.id
        	  params.coupon_Details_Id = this.couponInfo.coupon_Details_Id
        	}
        	if(this.machineId) {
        	  params.wash_Machine_Id = this.machineId
        	}
          let res = await this.$api.selfServiceCarWash.createOrder(params)
          console.log(res,'全自动')
          if(res.code === 200) {
            this.show = false
					  /* uni.redirectTo({
					    url: `/pages_commodity/payment/payment?orderNo=${res.data}&type=selfServiceCarWashCoupon&price=${this.amount}&machineId=${this.machineId}`
					  }) */
					  uni.navigateTo({
						  url: `/pages_commodity/newPay/newPay?orderNo=${res.data}&type=selfHelpWashCar&price=${this.amount}&machineId=${this.machineId}`
					  })
          } else {
					  uni.showToast({
					    icon: 'none',
					    title: res.msg
					  })
          }
        }catch(e){
        	//TODO handle the exception
        }
      }

    },

    more(){
      this.getBuyDiscountsList()
    },
    // 加载前、中、后
    moreStatus(status) {
		  this.loadStatus = status
    },
    //获取福利购列表
    async getBuyDiscountsList(){
      uni.showLoading({
			  title: '加载中',
        mask: true
      })
      this.loadStatus = 'loading'
		  try{
		    let data = {
				  'pageIndex': this.pageIndex,
				  'pageSize': 5
		    }
		    const res = await this.$api.maintenanceIndex.getBuyDiscountsList(data)

        this.list2 = [...this.list2, ...res.data.list]
        this.$nextTick(() => {
				  this.pageLoading = true
        })
        if(res.data.total <= 5){
				  this.loadStatus = 'nomore'
        }else{
				  this.moreStatus(res.data.list.length !== 0 ? 'loadmore' : 'nomore')
        }
        uni.hideLoading()
        if (res.data.list.length === 0) return false
        this.pageIndex += 1 // 当前页加1
		  }catch(e){
		    uni.hideLoading()
		  }
    },

    swiperChange(e){
      // console.log(this.cardList[this.currentSwiper])
      /* 	this.cardList = {
		  0: {
		    month: [], // 月
		    second: [], // 次
		    minute: [], // 分钟
		    recharge: [], // 计费
		    speed: [],//自动
		    standard: [],//标准
		    delicate: [],//精致
		    speedMonth: []
		  },
		  1: {
		    month: [], // 月
		    second: [], // 次
		    minute: [], // 分钟
		    recharge: [], // 计费
		    speed: [],//自动
		    standard: [],//标准
		    delicate: [],//精致
		    speedMonth: []
		  },
		  2: {
		    month: [], // 月
		    second: [], // 次
		    minute: [], // 分钟
		    recharge: [], // 计费
		    speed: [],//自动
		    standard: [],//标准
		    delicate: [],//精致
		    speedMonth: []
		  },
		} */
      this.currentSwiper = e.detail.current
      let list = Object.values(this.cardList[this.currentSwiper])
      if(list.findIndex(v => v.length!==0)===-1){
        this.getCardList()
      }
    },
    //跳转
    goPage(e){
      if(e===1){
        uni.getStorage({
				  key: 'Ztc_C_USER_INFO',
				  success: data => {
				    uni.navigateTo({
						  url: '/pages_userModule/myCoupon/index?mobile='+data.data.mobile
				    })
				  },
				  fail: () => {
				    uni.showToast({
				      title: '请登录！',
				      icon: 'none'
				    })
				  }
        })
      }else{
        this.currentSwiper = e
      }

    },
    transition(e) {
		  let dx = e.detail.dx
		  this.$refs.uTabs.setDx(dx)
    },
    animationfinish(e) {
		  let current = e.detail.current
		  this.$refs.uTabs.setFinishCurrent(current)
		  this.currentTab = current
    },
  }

}